import requests
import json
import logging
from utils import sync_retry

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

@sync_retry(retries=3, delay=1.0, backoff=2.0, exceptions=(requests.RequestException, json.JSONDecodeError))
def fetch_wscn_news():
    """
    从华尔街见闻API获取全球市场新闻数据并转换为Markdown格式
    """
    api_url = "https://api-one-wscn.awtmt.com/apiv1/content/lives?channel=global-channel&client=pc&limit=25&first_page=true&accept=live%2Cvip-live"
    
    logger.info("开始请求华尔街见闻API: %s", api_url)
    response = requests.get(api_url)
    response.raise_for_status()  # 检查请求是否成功
    logger.info("成功获取API响应，状态码: %d", response.status_code)
    
    data = response.json()
    logger.debug("API响应数据解析成功")
    
    markdown = []
    if 'data' in data and 'items' in data['data']:
        items_count = len(data['data']['items'])
        logger.info("获取到 %d 条新闻数据", items_count)
        
        for index, item in enumerate(data['data']['items'], 1):
            title = item.get('title', '').strip()
            content = item.get('content_text', '').strip()
            
            if title or content:
                logger.debug("处理第 %d/%d 条新闻", index, items_count)
                # 如果有标题，使用标题作为二级标题
                if title:
                    markdown.append(f"## {title}\n")
                # 添加内容
                if content:
                    markdown.append(f"{content}\n")
    else:
        logger.warning("API响应数据格式不符合预期")
        return ""
    
    result = "\n".join(markdown)
    logger.info("新闻数据处理完成，生成的Markdown长度: %d 字符", len(result))
    return result

if __name__ == '__main__':
    # 测试函数
    result = fetch_wscn_news()
    print(result)